<?php

/**
 * Desc: 登录注册控制器
 * Created by lwx
 * Date: 2018-08-14
 */

namespace App\Http\WechatAuth\Controllers;

use App\Api\BaseClass\Controller;
use App\Core\Facades\User as UserFacades;
use App\Http\WechatAuth\Classes\ShortMessage;
use App\Http\WechatAuth\Models\User;
use App\Http\WechatAuth\Models\MobileCode;
use App\Http\WechatAuth\Models\TeamMember;
use App\Http\WechatAuth\Models\UserIntegralLog;
use App\Http\WechatAuth\Models\UserCashRequestLog;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use App\Http\ManagerApi\Classes\CommissionCalculate;
use App\Http\ManagerApi\Models\PlatformSetting;
use App\Http\ManagerApi\Models\PlatformGoods;
use App\Http\ManagerApi\Models\PlatformGoodsCategory;
use App\Http\WechatAuth\Models\UserOrder;
use App\Http\ManagerApi\Models\PlatformRangeSetting;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class RegisterController extends Controller
{
    /**
     * 用户注册
     */
    public function register()
    {
        $rules = [
            ['user_name', 'required|string'],
            ['nick_name', 'required|string'],
            ['mobile', 'required'],
            ['id_card_no', 'required'],
            ['code', 'required'],
            ['recommend_code', 'required'],
            // ['password', 'required|string'],
            // ['province', 'required|string'],
            // ['city', 'required|string'],
            // ['district', 'required|string'],
            // ['address', 'required|string'],
            ['card_no', 'string'],
            // ['my_recommend_code', 'required'],
        ];

        $params = $this->form->camelFormOrFail($rules);
        $params['password'] = Crypt::encryptString('aa111111');

        // 校验验证码
        $code = MobileCode::where('mobile', $params['mobile'])->first();
        if (!isset($code) || $code['code'] !== $params['code']) {
            return $this->form->error('验证码错误，请重试！');
        }

        $max_diff_minute = 3;
        $diff_minutes = Carbon::now()->diffInMinutes($code['updated_at']);
        if ($max_diff_minute <= $diff_minutes) {
            return $this->form->error('验证码已过期');
        }

        // 校验推荐码
        $check_recommend_code = User::where('is_active', 1)->where('my_recommend_code', $params['recommend_code'])->firstOrFail();

        // 校验昵称是否唯一
        if (User::Where('nick_name', $params['nick_name'])->exists()) {
            return $this->form->error('该昵称已被注册');
        }

        DB::transaction(function () use ($params) {

            // 生成我的推荐码
            list($pre_word, $no) = preg_split('/([a-zA-Z]+)/', $params['recommend_code'], 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);

            $rand_no = mt_rand(10000, 99999);
            $params['my_recommend_code'] = $pre_word . $rand_no;
            $params['is_active'] = 0;

            unset($params['code']);
            User::create($params);
        }, 5);

        return $this->form->success('注册成功');
    }

    /**
     * 购买商品,激活
     */
    public function userAudit()
    {
        $rules = [
            ['goods_id', 'required|integer'],
            ['province', 'required'],
            ['city', 'required'],
            ['district', 'required'],
            ['address', 'required'],
        ];

        $params = $this->form->camelFormOrFail($rules);

        $user = UserFacades::user();

        if ($user->is_active == 1) {
            return $this->form->error('已激活，请勿重复操作');
        }

        // 商品信息
        $goods = PlatformGoods::findOrFail($params['goods_id']);

        if ($user->integral == 0 || $user->integral < $goods->goods_price) {
            return $this->form->error('金豆不足，无法激活');
        }

        DB::transaction(function () use ($user, $goods, $params) {

            $user->decrement('integral', $goods->goods_price, ['is_active' => 1]);

            // 插入积分记录表
            $create = [
                'uid' => $user->id,
                'changed_integral' => $goods->goods_price,
                'current_integral' => $user->integral,
                'flag' => 0,
                'type' => 8,
                'is_finished' => 1,
                'desc' => "账户激活"
            ];
            UserIntegralLog::create($create);

            // 平台设置
            $set = PlatformSetting::firstOrFail();
            // 插入积分记录表
            $create = [
                'uid' => $user->id,
                'changed_integral' => (int)($goods->goods_price * $set->service_charge_rate),
                'current_integral' => 0,
                'flag' => 1,
                'type' => 10,
                'is_finished' => 1,
                'desc' => "平台管理费"
            ];
            UserIntegralLog::create($create);

            // 直属上级信息
            $sup = User::where('my_recommend_code', $user->recommend_code)->firstOrFail();

            $order_count = UserOrder::whereDate('created_at', date('Y-m-d'))->count();
            // 插入用户订单表
            $create = [
                'uid' => $user->id,
                'sup_uid' => $sup->id,
                'order_no' => date('YmdHis') . $order_count + 1,
                'price' => $goods->goods_price,
                'order_snap' => json_encode(['id' => $goods->id, 'name' => $goods->goods_name, 'desc' => $goods->goods_introduction, 'image' => $goods->goods_image]),
                'province' => $params['province'],
                'city' => $params['city'],
                'district' => $params['district'],
                'address' => $params['address'],
            ];
            UserOrder::create($create);

            // 上级业绩增加
            //$sup->increment('total_achievement', $goods->goods_price);

            // 插入积分记录表
            // $create = [
            //     'uid' => $user->id,
            //     'changed_integral' => 522,
            //     'current_integral' => 0,
            //     'flag' => 1,
            //     'type' => 5,
            //     'is_finished' => 1,
            //     'desc' => "店铺服务费"
            // ];
            // UserIntegralLog::create($create);
            
            // 加入团队表
            TeamMember::create(['uid' => $sup->id, 'sub_uid' => $user->id]);

            // 计算佣金
            $calculate_class = new CommissionCalculate($sup->id, $user->id, $goods->goods_price);
            $calculate_class->calculateCommission();

        });

        return $this->form->success('激活成功');
    }

    /**
     * 金豆转让
     */
    public function saleIntegral()
    {
        $rules = [
            ['recommend_code', 'required'],
            ['changed_integral', 'required|integer'],
            ['password', 'required|between:4,50'],
            ['code', 'required'],
        ];

        $params = $this->form->camelFormOrFail($rules);

        $user = UserFacades::user();
        $to_user = User::where('my_recommend_code', $params['recommend_code'])->firstOrFail();

        // 校验验证码
        $code = MobileCode::where('mobile', $user->mobile)->first();
        if (!isset($code) || $code['code'] !== $params['code']) {
            return $this->form->error('验证码错误，请重试！');
        }

        $max_diff_minute = 3;
        $diff_minutes = Carbon::now()->diffInMinutes($code['updated_at']);
        if ($max_diff_minute <= $diff_minutes) {
            return $this->form->error('验证码已过期');
        }

        if ($params['password'] != Crypt::decryptString($user->password)) {
            return $this->form->error('密码验证错误');
        }

        if ($user->my_recommend_code == $params['recommend_code']) {
            return $this->form->error('金豆不可以转让给本人哟~');
        }

        if ($params['changed_integral'] <= 0) {
            return $this->form->error('转让金豆金额错误！');
        }

        if ($user->integral < $params['changed_integral']) {
            return $this->form->error('金豆不足');
        }

        DB::transaction(function () use ($user, $to_user, $params) {

            $user->decrement('integral', $params['changed_integral']);

            $to_user->increment('integral', $params['changed_integral']);

            // 插入积分记录表
            $create = [
                'uid' => $user->id,
                'changed_integral' => $params['changed_integral'],
                'current_integral' => $user->integral,
                'flag' => 0,
                'type' => 9,
                'is_finished' => 1,
                'desc' => "金豆转让给{$to_user->user_name}"
            ];
            UserIntegralLog::create($create);

            // 插入积分记录表
            $create = [
                'uid' => $to_user->id,
                'changed_integral' => $params['changed_integral'],
                'current_integral' => $to_user->integral,
                'flag' => 1,
                'type' => 9,
                'is_finished' => 1,
                'desc' => "来自{$user->user_name}金豆转让"
            ];
            UserIntegralLog::create($create);

            // 自动激活
            // if ($to_user->is_active == 0 && $to_user->integral >= $setting->active_fee) {

            //     $to_user->decrement('integral', $setting->active_fee, ['is_active' => 1]);

            //     // 插入积分记录表
            //     $create = [
            //         'uid' => $to_user->id,
            //         'changed_integral' => $setting->active_fee,
            //         'current_integral' => $to_user->integral,
            //         'flag' => 0,
            //         'type' => 3,
            //         'is_finished' => 1,
            //         'desc' => "账户激活"
            //     ];
            //     UserIntegralLog::create($create);

            //     // 插入积分记录表
            //     $create = [
            //         'uid' => $to_user->id,
            //         'changed_integral' => (int)($setting->register_fee * $setting->service_charge_rate),
            //         'current_integral' => 0,
            //         'flag' => 1,
            //         'type' => 4,
            //         'is_finished' => 1,
            //         'desc' => "平台管理费"
            //     ];
            //     UserIntegralLog::create($create);

            //     // 插入积分记录表
            //     $create = [
            //         'uid' => $to_user->id,
            //         'changed_integral' => 522,
            //         'current_integral' => 0,
            //         'flag' => 1,
            //         'type' => 5,
            //         'is_finished' => 1,
            //         'desc' => "店铺服务费"
            //     ];
            //     UserIntegralLog::create($create);
            
            //     // 获取直属上级
            //     $super = User::where('my_recommend_code', $to_user->recommend_code)->first();
            //     if (isset($super)) {

            //         // 加入团队表
            //         TeamMember::create(['uid' => $super->id, 'sub_uid' => $to_user->id]);

            //         // 计算佣金
            //         $calculate_class = new CommissionCalculate($super->id, $to_user->id);
            //         $calculate_class->calculateCommission();
            //     }
            // }
        });

        return $this->form->success('转让成功');
    }

    /**
     * 手机号绑定第一步，发送验证码
     */
    public function sendMobileCode()
    {
        $rules = [
            ['a', 'required|string']
        ];
        $params = $this->form->camelFormOrFail($rules);

        // 判断是否存在验证码
        $mobile_code = MobileCode::where('mobile', $params['a'])->first();
        // 如果存在判断是否在60秒内发送的
        if (isset($mobile_code)) {

            // 当前时间
            $now = Carbon::now();

            // 最后有效时间
            $lost_time = $mobile_code->created_at->addSeconds(60);

            // 如果还没有失效，就不能发送验证码
            if ($lost_time->gt($now) === true) {
                return $this->form->error('60秒内不能重复发送验证码～');
            }


        } else {
            $mobile_code = new MobileCode();
        }

        // 生成新的验证码
        $code = '';
        for ($i = 0; $i < 6; $i++) {
            $code .= random_int(0, 9);
        }

        // 更新|添加验证码记录
        $mobile_code->fill([
            'mobile' => $params['a'],
            'code' => $code
        ])->save();

        // 发送验证码

        with(new ShortMessage)->singleSend($mobile_code->mobile, "【亨梦科技】您的验证码是$mobile_code->code");
        return $this->form->success($code);
    }

    /**
     * 手机号绑定第二步，确认验证码
     */
    public function confirmMobileCode(AuthContract $auth)
    {
        $params = $this->form->checkParams(['mobile:min:11|max:11', 'code:min:6|max:6s']);

        // 判断验证码手机号是否匹配
        $mobile_code = MobileCode::where($params)->first();

        if (!isset($mobile_code)) {
            return $this->form->error('验证码与手机号不匹配～');
        };

        // 把手机号加入到用户信息中
        $auth->user->mobile = $params['mobile'];
        $auth->user->save();

        return $this->form->success('绑定成功～');
    }

    /**
     * 获取所属推荐码人的姓名电话
     */
    public function info()
    {
        $rules = [
            ['recommend_code', 'required|string'],
        ];
        $params = $this->form->camelFormOrFail($rules);
        $info = User::where('my_recommend_code', $params['recommend_code'])->first();
        if (!isset($info)) {
            return $this->form->error('推荐码错误');
        }

        $userinfo['user_name'] = $info->user_name;
        $userinfo['mobile'] = $info->mobile;
        return $this->form->datas($userinfo);
    }

    /**
     * 获取个人信息
     */
    public function userInfoGet()
    {
        $user = UserFacades::user();
        $level = PlatformRangeSetting::where('condition', '<=', $user->total_achievement / 10000)
            ->orderBy('condition', 'desc')
            ->value('level');
        // 级别
        $user->level = isset($level) ? $level : '创客';

        return $this->form->getMessage($user);
    }

    /**
     * 编辑个人信息
     */
    public function userInfoUpdate()
    {
        $rules = [
            ['mobile', 'string'],
            ['card_no', 'string'],
            ['province', 'string'],
            ['city', 'string'],
            ['district', 'string'],
            ['address', 'string'],
        ];
        $params = $this->form->camelFormOrFail($rules);
        return $this->form->updateMessage(User::where('id', UserFacades::user()->id)->update($params));
    }

    /**
     * 发起提现
     */
    public function putForward()
    {
        $rules = [
            ['changed_integral', 'required|integer'],
            ['card_no', 'required|integer'],
            ['bank_name', 'required|string'],
            ['user_name', 'required|string'],
            ['mobile', 'required|integer'],
            ['code', 'required'],
        ];
        $params = $this->form->camelFormOrFail($rules);

        $user_model = UserFacades::user();

        // 校验验证码
        $code = MobileCode::where('mobile', $user_model->mobile)->first();
        if (!isset($code) || $code['code'] !== $params['code']) {
            return $this->form->error('验证码错误，请重试！');
        }

        $max_diff_minute = 3;
        $diff_minutes = Carbon::now()->diffInMinutes($code['updated_at']);
        if ($max_diff_minute <= $diff_minutes) {
            return $this->form->error('验证码已过期');
        }

        DB::beginTransaction();
        try {
            if ($params['changed_integral'] <= 0 || $params['changed_integral'] % 100) {
                return $this->form->error('提现必须是100的倍数，请重试！！！');
            }

            $user_model->decrement('integral', $params['changed_integral']);
            if ($user_model->integral < 0) {
                throw new \Exception("金豆不足，无法提现！");
            }
            // 插入提现申请表
            $insert = [
                'uid' => $user_model->id,
                'user_name' => $params['user_name'],
                'mobile' => $params['mobile'],
                'changed_integral' => $params['changed_integral'],
                'card_no' => $params['card_no'],
                'bank_name' => $params['bank_name'],
                'status' => 0,
            ];
            $cash = UserCashRequestLog::create($insert);
            // 插入积分表
            $create = [
                'uid' => $user_model->id,
                'changed_integral' => $params['changed_integral'],
                'current_integral' => $user_model->integral,
                'flag' => 0,
                'type' => 7,
                'is_finished' => 0,
                'desc' => '账户提现',
                'cash_log_id' => $cash->id,
            ];
            UserIntegralLog::create($create);
        } catch (\Exception $e) {
            DB::rollback();
            return $this->form->error($e->getMessage());
        }
        DB::commit();
        return $this->form->success('提现申请成功，请耐心等待审核！');
    }

    /**
     * 积分明细列表
     */
    public function listForward()
    {
        $rules = [
            ['offset', 'required|integer'],
            ['limit', 'required|integer'],
            ['type', 'integer'],
            ['start', 'date'],
            ['end', 'date'],
        ];

        $params = $this->form->camelFormOrFail($rules);
        $search_params = [
            ['orderBy', 'created_at', 'desc'],
            ['orderBy', 'id', 'desc'],
            ['where', 'uid', UserFacades::user()->id],
            ['where', 'type', '$type'],
            ['where', 'created_at', '>=', '$start'],
            ['where', 'created_at', '<=', '$end'],
            ['whereNotIn', 'type', [5, 8, 10]]
        ];
        $userintegrallog = (new UserIntegralLog)->pagination($params, $search_params);

        if (isset($params['type']) && !empty($params['type'])) {
            $userintegrallog['zhichu'] = UserIntegralLog::where('uid', UserFacades::user()->id)
                ->where('type', $params['type'])
                ->where('flag', 0)
                ->where('is_finished', 1)
                ->sum('changed_integral');
            $userintegrallog['shouru'] = UserIntegralLog::where('uid', UserFacades::user()->id)
                ->where('type', $params['type'])
                ->where('flag', 1)
                ->where('is_finished', 1)
                ->sum('changed_integral');
            $userintegrallog['type'] = $params['type'];
        }

        return $this->form->getMessage($userintegrallog);
    }

    /**
     * 提现记录详情
     */
    public function cashDetail()
    {
        $rules = [
            ['id', 'required|integer'],
        ];
        $params = $this->form->camelFormOrFail($rules);
        $data = UserIntegralLog::findOrFail($params['id']);
        if ($data->form_sub_id != 0) {
            $data['form_sub_name'] = User::findOrFail($data->form_sub_id)->user_name;
        }
        if ($data->cash_log_id != 0) {
            $data['cash_log'] = UserCashRequestLog::findOrFail($data->cash_log_id);
        }
        return $this->form->datas($data);
    }

    /**
     * 用户修改密码
     */
    public function passwordUpdate()
    {
        $rules = [
            ['password', 'required|string'],
            ['new_password', 'required|string'],
            ['confirm_password', 'required|string']
        ];
        $params = $this->form->camelFormOrFail($rules);
        $user_model = UserFacades::user();
        $user = User::where('id', $user_model->id)->first();
        // 判断原密码是否正确
        if (Crypt::decryptString($user->password) != $params['password']) {
            return $this->form->error('原密码错误');
        }
        // 判断两次密码是否一致
        if ($params['new_password'] !== $params['confirm_password']) {
            return $this->form->error("两次输入的密码不一致");
        }
        // 新旧密码不能相同
        if ($params['new_password'] == $params['password']) {
            return $this->form->error('新旧密码不能相同');
        }
        // 加密新密码
        $user->password = Crypt::encryptString($params['new_password']);
        $user->save();
        // $update = User::where('id', $user->id)->update(['password' => $params['new_password']]);
        // if (empty($update)) {
        //     return self::error('更新失败，请重试');
        // }
        return $this->form->updateMessage($user);
    }

    /**
     * 获取直属下级成员
     */
    public function teamMember()
    {
        $rules = [
            ['offset', 'required|integer'],
            ['limit', 'required|integer']
        ];
        $params = $this->form->camelFormOrFail($rules);
        $search_params = [
            ['orderBy', 'created_at', 'desc']
        ];
        $user = UserFacades::user();
        $team = TeamMember::where('uid', $user->id)->get(['sub_uid']);
        $data['user_name'] = TeamMember::where('sub_uid', $user->id)->first();
        if (!empty($data['user_name'])) {
            $data['user_name'] = User::where('id', $data['user_name']->uid)->first()->user_name;
        } else {
            $data['user_name'] = '';
        }
        $data['team'] = User::whereIn('id', $team)
            ->offset($params['offset'])
            ->limit($params['limit'])
            ->get();
        foreach ($data['team'] as $val) {
            $val['team'] = TeamMember::where('uid', $val->id)->get(['sub_uid']);
            $this->all += $val['team']->count();
            $this->all($val['team']);
            $val['all'] = $this->all;
            $this->all = 0;
            unset($val['team']);
        }
        $message['total'] = User::whereIn('id', $team)->count();
        $message['rows'] = $data;
        return $this->form->getMessage($message);
    }
    private $all = 0;

    public function all($array)
    {
        if (!empty($array)) {
            foreach ($array as $val) {
                $team = TeamMember::where('uid', $val->sub_uid)->get(['sub_uid']);
                $this->all += count($team);
                $this->all($team);
            }
        }
    }

    /**
     * 获取分类列表
     */
    public function listCategory()
    {
        return $this->form->getMessage(PlatformGoodsCategory::where('parent_id', 0)->get());
    }

    /**
     * 获取指定类别商品
     */
    public function listGoods()
    {
        $rules = [['primary_category_id', 'required|integer']];

        $params = $this->form->camelFormOrFail($rules);

        return $this->form->getMessage(PlatformGoods::where('primary_category_id', $params['primary_category_id'])->get());
    }
    /**
     * 生成分享二维码
     */
    public function generateShareQrcode()
    {
        $rules = [['uid', 'required|integer']];

        $params = $this->form->camelFormOrFail($rules);

        $user = User::findOrFail($params['uid']);

        $png = QrCode::format('png')->size(400)->generate('http://dspc.anasit.com/register?myRecCode=' . $user->my_recommend_code);

        echo $png;
    }
}